package server;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import Logic.SendMail;
/**
 * this class implemnts thred that calculated statistics once a day
 * @author Ron Shenkerman
 * @author Gabi Revah
 * @author Aviad Almog
 * @author Ivan Onyshchenko
 */
public class Lendingreport implements Runnable{

	private static final int oneday=86400000;
	int date,flag,j=1,wantedcount,normalcount;
	String str,subscriberid,mailto;
	Date returndate,today1;
	Statement stmt,stm;
	

	@SuppressWarnings("deprecation")
	@Override
	public void run() {
		
		
		while(EchoServer.echoserveron){
			
			try 
				{
				System.out.println(j);	
				
			System.out.println("getting book detail for viewing");
			//Statement stmt,stmt1;
			Statement stmt,stmt1;
			SQLConnection conn = new  SQLConnection();
			stmt = conn.getConnection().createStatement();
			stmt1 = conn.getConnection().createStatement();
			
					
					
			ResultSet rs1=stmt.executeQuery("SELECT * FROM db1.lending,db1.books,db1.bookscopies WHERE lending.Lend='"+"no"+"' AND lending.CopyId=bookscopies.copyId AND bookscopies.BID=books.ID ;");
			//ResultSet rs= stmt1.executeQuery("SELECT * FROM db1.Lending,db1.bookscopies  WHERE  bookscopies.CopyId=Lending.copyid AND SubscriberId='"+str[1]+"' AND Lend='"+"yes"+"';");
			PreparedStatement ps9 = conn.getConnection().prepareStatement("update db1.lendReport set wantedday = ?  where serial = ?");
			PreparedStatement ps8 = conn.getConnection().prepareStatement("update db1.lendReport set normalday = ?  where serial = ?");
			try {
					
					if(j==31)
						j=1;
						while(rs1.next()&j<=30){ 
						  
						//  System.out.println(j);
								if(rs1.getString(19).equals("Yes")){
								
									wantedcount=wantedcount+rs1.getDate(6).getDate()-rs1.getDate(4).getDate();
									
								
								}
									else{
											
										normalcount=normalcount+rs1.getDate(6).getDate()-rs1.getDate(4).getDate();
										
										}
								}
					ps9.setInt(1, wantedcount);
					ps9.setInt(2,j);
					ps9.executeUpdate();
					ps8.setInt(1, normalcount);
					ps8.setInt(2,j);
					ps8.executeUpdate();
					ps9.close();
					ps8.close();
					rs1.close();
					
					}
						catch (SQLException e)
								{	
								e.printStackTrace();
								}
			
	}
		catch (Exception ex )
		{
			ex.printStackTrace();
			}
			
	
			try 
			{
				Thread.sleep(oneday);//oneday
				j++;
				wantedcount=0;
				normalcount=0;
				
				
			} 
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
		}
	}

	
}
